import numpy as np
import matplotlib.pyplot as plt
from keras.applications import inception_v3, resnet50, mobilenet
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.imagenet_utils import decode_predictions

# 加载模型
# 若路径C:\Users\Administrator\.keras\models下没有预训练模型文件（.h5），将自动从网络（GitHub）下载。
inception_model = inception_v3.InceptionV3(weights='imagenet')
resnet50_model = resnet50.ResNet50(weights='imagenet')
mobilenet_model = mobilenet.MobileNet(weights='imagenet')

# 待预测的图片
image_path = '手机.jpg'
plt.imshow(load_img(image_path))
plt.show()

# 以PIL格式加载图像，注意ImageNet模型只能处理224x224图片
original = load_img(image_path, target_size=(224, 224))
image_batch = np.expand_dims(img_to_array(original), axis=0)

# ResNet50
processed_image = resnet50.preprocess_input(image_batch.copy())
predictions = resnet50_model.predict(processed_image)
prediction_resnet = decode_predictions(predictions, top=1)
label_resnet = prediction_resnet[0][0][1]
possible_resnet = prediction_resnet[0][0][2]
print("ResNet50", label_resnet, possible_resnet)

# MobileNet
processed_image = mobilenet.preprocess_input(image_batch.copy())
predictions = mobilenet_model.predict(processed_image)
prediction_mobilnet = decode_predictions(predictions, top=1)
label_mobilnet = prediction_mobilnet[0][0][1]
possible_mobilnet = prediction_mobilnet[0][0][2]
print("MobileNet", label_mobilnet, possible_mobilnet)

# InceptionV3
# 初始网络的输入大小与其他网络不同。 它接受大小的输入（299,299）。
original = load_img(image_path, target_size=(299, 299))
image_batch = np.expand_dims(img_to_array(original), axis=0)
processed_image = inception_v3.preprocess_input(image_batch.copy())
predictions = inception_model.predict(processed_image)
prediction_inception = decode_predictions(predictions, top=1)
label_inception = prediction_inception[0][0][1]
possible_inception = prediction_inception[0][0][2]
print("InceptionV3", label_inception, possible_inception)

